import { get } from '../axios'
import wx from 'weixin-js-sdk'

export default function(share) {
    let isIos = ()=>{
        return /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent) && 
            !(navigator.userAgent.indexOf("wechatdevtools") > -1);
    }
    // 记录进入app的url，后面微信sdk
    if (window.entryUrl === undefined) {
        window.entryUrl = location.href.split('#')[0]
    }
  // 进行签名的时候
    let url = isIos() ? window.entryUrl : location.href.split('#')[0] 

    if (navigator.userAgent.toLowerCase().indexOf('micromessenger') == -1) {
        return
    }
    
    get(`/mem/wechat-share?url=${encodeURIComponent(url)}`)
    .then(json => {
        wx.config({...json, debug: false})  

        //微信初始化失败
        wx.error(function (res) {
            console.log(res)
            alert("wx err:" + res.errMsg+'-----'+url);
            // window.location.reload();
        })

        wx.ready(() => {

            if (/(\/login)|(\/register\/\w+)/.test(window.location.pathname)) {
                wx.hideMenuItems({
                    menuList: ["menuItem:share:appMessage", "menuItem:share:timeline", "menuItem:share:qq", 
                        "menuItem:share:weiboApp", "menuItem:share:facebook", "menuItem:share:QZone"]
                });
            } else {
                wx.showMenuItems({
                    menuList: ["menuItem:share:appMessage", "menuItem:share:timeline", "menuItem:share:qq", 
                        "menuItem:share:weiboApp", "menuItem:share:facebook", "menuItem:share:QZone"]
                });
            }
            //分享给朋友
            wx.onMenuShareAppMessage(share)

            //分享到朋友圈
            wx.onMenuShareTimeline(share)

        })                     
    })
    .catch(e=>console.log(e))

}

export function initWxConfig() {
    let url = window.location.href.split('#')[0]
    
    get(`/mem/wechat-share?url=${encodeURIComponent(url)}`)
    .then(json => {
        wx.config({...json, debug: false})  

        //微信初始化失败
        wx.error(function (res) {
            console.log(res)
            alert("wx err:" + res.errMsg+'-----'+url);
            // window.location.reload();
        })

        wx.ready(() => {
           console.log('initial wechat config successfully')
        })                     
    })
    .catch(e=>console.log(e))
}